package com.plug.common.quartz;

import com.plug.common.jdbc.JDBCInfoBean;
import com.plug.common.quartz.job.QuartzJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

/**
 * Created by slayes on 2017/1/9.
 */
public class QuartzManager {
    private static SchedulerFactory schedulerFactory = new StdSchedulerFactory();//创建一个SchedulerFactory工厂实例
    private final static String JOB_GROUP_NAME = "Quartz_Job_Group_Name";//任务默认组
    private final static String TRIGGER_GROUP_NAME = "Quartz_Trigger_Group_Name";//触发器默认组
    private static Logger logger = LoggerFactory.getLogger(QuartzManager.class);//日志


    /**
     * 添加任务的方法
     * @param jobName 任务名
     * @param triggerName 触发器名
     * @param jobClass 执行任务的类
     * @param seconds 间隔时间(以秒为单位)
     * @throws SchedulerException
     */
    public static void addJob(String jobName,String triggerName,Class<? extends Job> jobClass,int seconds) throws SchedulerException{
        Scheduler scheduler = schedulerFactory.getScheduler();//通过SchedulerFactory构建Scheduler对象
        //用于描叙Job实现类及其他的一些静态信息，构建一个作业实例
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, JOB_GROUP_NAME).build();
        //构建一个触发器，规定触发的规则
        Trigger trigger = TriggerBuilder.newTrigger()//创建一个新的TriggerBuilder来规范一个触发器
                .withIdentity(triggerName, TRIGGER_GROUP_NAME)//给触发器起一个名字和组名
                .startNow()//立即执行
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(seconds)//时间间隔  单位：秒
                        .repeatForever()//一直执行
                ).build();//产生触发器
        scheduler.scheduleJob(jobDetail, trigger);//向Scheduler中添加job任务和trigger触发器
        logger.debug("==================添加任务(addJob):任务名:{},触发器名:{},执行类名:{},执行间隔时间:{}=================",
                jobName, triggerName, jobClass.getPackage(), seconds);
//        scheduler.start();//启动
    }


    /**
     * 暂停任务
     * @param jobName 任务名称
     * @throws SchedulerException
     */
    public static void pauseJob(String jobName) throws SchedulerException {
        Scheduler scheduler = schedulerFactory.getScheduler();
        JobKey jobKey = JobKey.jobKey(jobName, JOB_GROUP_NAME);
        logger.debug("=================暂停任务(task job pause):{}==========================", jobName);
        scheduler.pauseJob(jobKey);
    }

    /**
     * 批量暂停任务
     * @param groupMatcher
     * @return void
     * @throws SchedulerException
     */
    public static void batchPauseJob(GroupMatcher<JobKey> groupMatcher) throws SchedulerException {
        Scheduler scheduler = schedulerFactory.getScheduler();
        logger.debug("=================批量暂停任务(task job batchPauseJob)==========================");
        scheduler.pauseJobs(groupMatcher);
    }

    /**
     * 暂停所有任务
     * @return void
     * @throws SchedulerException
     */
    public static void pauseAllJob() throws SchedulerException {
        Scheduler scheduler = schedulerFactory.getScheduler();
        scheduler.pauseAll();
        logger.debug("=================暂停所有任务(task job pauseAllJob)==========================");
    }

    /**
     * 关闭所有任务
     * @return void
     * @throws SchedulerException
     */
    public static void shutdownJobAll() {
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            if (!scheduler.isShutdown()) {
                scheduler.shutdown();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 恢复任务
     * @param jobName 任务名称
     * @return void
     * @throws SchedulerException
     */
    public static void resumeJob(String jobName) throws SchedulerException {
        Scheduler scheduler = schedulerFactory.getScheduler();
        JobKey jobKey = JobKey.jobKey(jobName, JOB_GROUP_NAME);
        logger.debug("=====================恢复任务(resumeJob):{}=======================", jobName);
        scheduler.resumeJob(jobKey);
    }

    /**
     * 恢复所有任务
     * @return void
     * @throws SchedulerException
     */
    public static void resumeAllJob() throws SchedulerException {
        Scheduler scheduler = schedulerFactory.getScheduler();
        logger.debug("==================恢复所有任务=======================");
        scheduler.resumeAll();
    }

    public static void addTaskAll(){
        Properties pro = new Properties();
        try {
            pro.load(QuartzManager.class.getClass().getResourceAsStream("/config/properties/plug-core.properties"));
            Class.forName(pro.getProperty("jdbc.driverClassName"));
            Connection con = DriverManager.getConnection(pro.getProperty("jdbc.url"), pro.getProperty("jdbc.username"), pro.getProperty("jdbc.password"));
            PreparedStatement ps = con.prepareStatement("select * from plug_contrast");
            ResultSet rs = ps.executeQuery();
            while (rs.next()){
                addJob(rs.getString("task_id"),rs.getString("task_id"), QuartzJob.class, rs.getInt("timer"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除任务
     * @param jobName 任务名
     * @return void
     * @throws SchedulerException
     */
    public static void deleteJob(String jobName) throws SchedulerException {
        Scheduler scheduler = schedulerFactory.getScheduler();
        JobKey jobKey = JobKey.jobKey(jobName, JOB_GROUP_NAME);
        logger.debug("==================删除任务(deleteJob):{}=======================", jobName);
        scheduler.deleteJob(jobKey);
    }

    /**
     * 检测任务是否存在
     * @param jobName 任务名称
     * @throws SchedulerException
     * @return boolean
     * @throws SchedulerException
     */
    public static boolean checkJobExist(String jobName) throws SchedulerException {
        Scheduler scheduler = schedulerFactory.getScheduler();
        JobKey jobKey = JobKey.jobKey(jobName, JOB_GROUP_NAME);
        return scheduler.checkExists(jobKey);
    }
    public static void startAll() throws SchedulerException {
        schedulerFactory.getScheduler().start();
    }


    public static void main(String[] args) throws SchedulerException, InterruptedException {
        QuartzManager.addJob("test1", "aaaa", Test1.class, 5);
        QuartzManager.startAll();
  /*      QuartzManager.pauseJob("test1");
        Thread.sleep(10000);
        QuartzManager.resumeJob("test1");*/

//        if(QuartzManager.checkJobExist("test1")){
//            System.out.println("yes");
//        }
//        QuartzManager.deleteJob("test1");
//        if(QuartzManager.checkJobExist("test1")){
//            System.out.println("yes");
//        }else{
//            System.out.println("no");
//        }
       /*GroupMatcher<JobKey> groupMatcher=new GroupMatcher();
        groupMatcher.jobGroupEndsWith("");*/
        /* Thread.sleep(30000);
        //QuartzManager.pauseJob("test1");
        QuartzManager.deleteJob("test1");
        Thread.sleep(30000);
        //QuartzManager.resumeJob("test1");
        QuartzManager.startAll();*/
//        QuartzManager.addJob("test1", "aaaa", TestJob.class, 5);
//        QuartzManager.addJob("test2", "aaaaa", TestJob.class, 3);
//        QuartzManager.addJob("test3", "aaaa3", TestJob.class, 6);
//        Thread.sleep(30000);
//        Thread.sleep(10000);
  //      QuartzManager.pauseJob("test1");
//        QuartzManager.startAll();
//        QuartzManager.resumeAllJob();
    }

}
